/**
 * 
 */
package com.effectivcrm.startup;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.effectivcrm.domain.ui.Form;
import com.effectivcrm.domain.ui.Page;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;



/**
 * @author Dhrubo
 *
 */

public class ModelEnhancingInterceptor implements HandlerInterceptor {
	
	@Autowired
	@Qualifier("hazelCastClient")
	private HazelcastInstance client;

	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
		//Get Page meta info and populate model to access in page
		String url = request.getRequestURI();
		
		System.out.println("URL = " + url);
		
		IMap<String,Page> pageMap = client.getMap("pages");
		
		Page page = pageMap.get(url);
		
		System.out.println("##### page = " + page);
		System.out.println("##### modelAndView = " + modelAndView);
		if(page != null)
			modelAndView.addObject(page);
		
		IMap<String, Form> formMap = client.getMap("forms");
		Form form = formMap.get(url);
		System.out.println("##### form = " + form);
		if(form != null) {
			modelAndView.addObject(form);
		}
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		
		return true;
	}
	
	

}
